package com.xxxx.server.service.impl;

import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;
import com.xxxx.server.pojo.OSSConstants;
import com.xxxx.server.service.IOssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssserviceImp implements IOssService {
    @Override
    public String uploadfile(MultipartFile file) {
        String endpoint= OSSConstants.END_POINT;
        String accessKeyId=OSSConstants.ACCESS_KEY_ID;
        String accessKeySecret= OSSConstants.ACCESS_KEY_SECRET;
        String bucketName=OSSConstants.BUCKET_NAME;
        OSS oss=null;

        try {
            oss=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            InputStream inputStream=file.getInputStream();
            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");
            String datepath=dateFormat.format(new Date());

            String  originname=file.getOriginalFilename();
            String  filename= UUID.randomUUID().toString();
            String  suffix=originname.substring(originname.lastIndexOf("."));
            String newName=filename+suffix;
            String fileUrl=datepath+"/"+newName;
            oss.putObject(bucketName, fileUrl, inputStream);
            return "https://"+bucketName+"."+endpoint+"/"+fileUrl;
        } catch (IOException e) {
            return "fial";
        }finally {
            oss.shutdown();
        }


    }
}
